﻿/*** MainForm - FlashFurc
 * ---
 * Author: IceDragon <icedragon@quickfox.org>
 * Web:    www.icerealm.org
 * ---
 * 
 * Copyright (c) 2010, IceRealm.org
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   # Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   # Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   # Neither the name of the IceRealm.org nor the names of its contributors
 *     may be used to endorse or promote products derived from this software
 *     without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace FlashFurc
{
    public partial class MainForm : Form
    {
        enum InstallSource { Existing, FurcSetup };

        FFIExisting ffiExisting = new FFIExisting();
        FFIRCH2 ffiRCH2 = null;
        InstallSettings settings = new InstallSettings();
        Dictionary<string, List<FileInfo>> CharacterList = new Dictionary<string, List<FileInfo>>();

        public MainForm()
        {
            InitializeComponent();

            // Set the extra options checkboxes based on the initial Settings
            // values.
            settings.CopySettings = cbCopySettings.Checked;
            settings.CopyLogs = cbCopyLogs.Checked;
            settings.CopyCacheData = cbCopyCache.Checked;

            // Locate and present all the available characters.
            ListCharacters();

            // Determine if "existing" option is available and set initial
            // install source.
            rbExistingInstall.Enabled = ffiExisting.Available;
            SetInstallSource(
                    rbExistingInstall.Enabled ? InstallSource.Existing : InstallSource.FurcSetup
                );
        }

        /// <summary>
        /// Sets/Changes the install destination path text, as well as enabling
        /// the "Install" button if it was previously disabled.
        /// </summary>
        /// <param name="path">New target path</param>
        private void SetInstallPath(string path)
        {
            txtDestination.Text = path;
            btnInstall.Enabled = true;
        }

        /// <summary>
        /// Sets/Changes the install source settings.
        /// 
        /// NOTE: If the existing install source was determined as unavailable,
        ///       it will not be settable here!
        /// </summary>
        /// <param name="source">Install source to use</param>
        private void SetInstallSource(InstallSource source)
        {
            // If they're trying an existing install and it's not available,
            // force a change of choice.
            if (!rbExistingInstall.Enabled)
            {
                if (source == InstallSource.Existing)
                    source = InstallSource.FurcSetup;
                if (rbExistingInstall.Checked)
                    rbFurcSetup.Checked = true;
            }

            bool enableCopyOptions = source == InstallSource.Existing;

            cbCopySettings.Enabled = enableCopyOptions;
            cbCopyLogs.Enabled = enableCopyOptions;
            cbCopyCache.Enabled = enableCopyOptions;
        }


        /// <summary>
        /// Locate and list all the Furcadia characters we can find.
        /// </summary>
        private void ListCharacters()
        {
            Dictionary<FileInfo, string> characters = CharacterScanner.GetCharacters();

            CharacterList.Clear();
            listCharacters.SuspendLayout();
            foreach (FileInfo fi in characters.Keys)
            {
                string name = characters[fi];
                if (!CharacterList.ContainsKey(name))
                    CharacterList[name] = new List<FileInfo>();
                CharacterList[name].Add(fi);

                if (!listCharacters.Items.Contains(name))
                {
                    int index = listCharacters.Items.Add(name);
                    listCharacters.SetSelected(index, true);
                }
            }
            listCharacters.ResumeLayout();
        }

        private void Install()
        {
            InstallForm iform;
            settings.InstallTarget = txtDestination.Text;

            if (rbFurcSetup.Checked)
            {
                // Pick a furcsetup.exe to read the data from.
                ofdFurcSetup.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                while (true)
                {
                    if (ofdFurcSetup.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                        return;

                    try
                    {
                        ffiRCH2 = new FFIRCH2(ofdFurcSetup.FileName);
                        break;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                // Pass the settings over.
                ffiRCH2.Settings = settings;

                // Prime the install interface dialog.
                iform = new InstallForm();
                iform.Installer = ffiRCH2;
            }
            else
            {
                // Pass the settings over.
                ffiExisting.Settings = settings;

                // Prime the install interface dialog.
                iform = new InstallForm();
                iform.Installer = ffiExisting;
            }

            // If we should include character files, add them on.
            if (cbCopyCharacters.Checked)
            {
                foreach (string name in listCharacters.SelectedItems)
                {
                    foreach (FileInfo fi in CharacterList[name])
                    {
                        iform.Installer.CharacterFiles.Add(fi);
                    }
                }
            }

            // Show the dialog and let it run.
            iform.ShowDialog();
        }

        #region Event Handlers
        /*** Buttons ***/
        private void btnAbout_Click(object sender, EventArgs e)
        {
            About dlgAbout = new About();
            dlgAbout.ShowDialog();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (fbDestination.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                SetInstallPath(fbDestination.SelectedPath);
        }

        private void btnInstall_Click(object sender, EventArgs e)
        {
            Install();
        }

        /*** Radio Buttons ***/
        private void rbFurcSetup_CheckedChanged(object sender, EventArgs e)
        {
            SetInstallSource(InstallSource.FurcSetup);
        }

        private void rbExistingInstall_CheckedChanged(object sender, EventArgs e)
        {
            SetInstallSource(InstallSource.Existing);
        }

        /*** Checkboxes ***/
        private void cbCopyCharacters_CheckedChanged(object sender, EventArgs e)
        {
            grpCharacters.Enabled = cbCopyCharacters.Checked;
        }

        private void cbCopySettings_CheckedChanged(object sender, EventArgs e)
        {
            settings.CopySettings = cbCopySettings.Checked;
        }

        private void cbCopyLogs_CheckedChanged(object sender, EventArgs e)
        {
            settings.CopyLogs = cbCopyLogs.Checked;
        }

        private void cbCopyCache_CheckedChanged(object sender, EventArgs e)
        {
            settings.CopyCacheData = cbCopyCache.Checked;
        }
        #endregion
    }
}
